<template>
	<view class="_abbr">
		<view class="public">
			<view class="detail">
				<view class="main_body_view main_body_view_title">
					<u-row>
						{{dataForm.workOrderId}}
					</u-row>
				</view>
				<view class="main_body_view main_body_view_view">
					客户：{{dataForm.customerCompanyName}}
				</view>
				<!-- <view class="main_body_view main_body_view_view">
					时间：{{dataForm.preArriveCustomerTime|formatDate('MM-dd HH:mm')}}
				</view>
				<view class="main_body_view">
					联系：{{dataForm.customerCompanyConnUsername}}/{{dataForm.customerCompanyConnUserTel}}
				</view>
				<view class="main_body_view">地址：{{dataForm.province}}/{{dataForm.city}}/{{dataForm.district}}</view>
				<view class="main_body_view">{{dataForm.recycleAddress||''}}</view> -->
				<text class="main_body_view">备注：{{dataForm.dispWorkOrderRemark||"暂无其它备注"}}</text>
			</view>
		</view>
		<view class="public">
			<!-- <view>现场要求：<text :key="index" v-for="(item, index) in dataForm.recycleLiveRequest">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.recycleLiveRequestOther||"无"}}</view>
			<view>现场数据：<text :key="index" v-for="(item, index) in dataForm.recycleDataDestroyType">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.recycleDataDestroyTypeOther||"无"}}</view> -->
			<view>检测要求：<text :key="index" v-for="(item, index) in dataForm.testDeviceRequest">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.testDeviceRequestOther||"无"}}</view>
			<view>检测数据：<text :key="index" v-for="(item, index) in dataForm.testDataDestroyType">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.testDataDestroyTypeOther||"无"}} </view>
			<!-- <view>携带设备：<text :key="index" v-for="(item, index) in dataForm.recycleTakeDevice">{{item.remark}}/</text>
			</view>
			<view>其他：{{dataForm.recycleTakeDeviceOther||"无"}}</view> -->
		</view>
		<view class="public">
			<view>
				<view class="device-count">
					<view v-for="(item, index) in deviceTypeList" :key="index">
						<view class="device-item">
							<span>{{item.deviceType}}</span>
							<span>{{item.countType || 0}}/{{item.sumCountType || 0}}</span>
						</view>
					</view>
				</view>
				<view class="scan-item scan-item1">
					<input
						:focus="isFocus" 
						placeholder="扫描或输入二维码" 
						:value="deviceForm.deviceQr" 
						@blur="confirm" 
						type="text" 
						class="input">
					<view class="right-icon">
						<view class="icon" @click="doScan1">
							<u-icon size="30" name="scan"></u-icon>
						</view>
					</view>
				</view>
				<view class="scan-item scan-item1" style="display: flex;flex-direction: column;">
					<view style="display: flex;">
						<view class="add-attachment" @click="handleAddAttachment">新增配件</view>
						<view class="add-attachmentBasic" @click="handleAddProperiesValue">新增基础属性值</view>
					</view>
					<view class="item-container">
						<view
						  v-for="(item, index) in attachmentList"
						  :key="index"
						  class="item"
						>
						  <view style="display: flex; align-items: center;">
							{{ item.deviceProperties }}: {{ item.deviceModel }}
							<span @click="handleCancelAttachment(item)" class="cancel">×</span>
						  </view>
						</view>
					</view>
					<view class="item-container">
						<view
						  v-for="(item, index) in detailPropertiesValueList"
						  :key="index"
						  class="item"
						>
						  <view style="display: flex; align-items: center;">
							{{ item.devicePropertiesEn }}: {{ item.propertiesValue }}
							<!-- <span @click="handleCancelPropertiesValue(item)" class="cancel">×</span> -->
						  </view>
						</view>
					</view>
					<u-modal 
						:show="isAttachmentOpen" 
						title="新增配件"
						@confirm="handleConfirmAdd"
						@cancel="handleCancel" 
						show-cancel-button
						mask-close-able
						>
						<view>
							<u-form :model="attachmentForm" ref="uForm" style="width: 100%;">
								<u-form-item>
									<text class="attach-item" v-if="!attachmentForm.deviceProperties" @click="devicePropertiesShow = true;">选择配件类型</text>
									<text class="attach-item" v-else @click="devicePropertiesShow = true;">{{attachmentForm.deviceProperties}}</text>
									<u-picker :show="devicePropertiesShow" :columns="propertiesList" @confirm="attachmentConfirm" keyName="label" @cancel="cancel"></u-picker>
								</u-form-item>
								<u-form-item>
									<view class="put" @click="getDeviceModelList()">
									<u-input placeholder="配件型号"  @click="getDeviceModelList()" class="put-w"
										v-model="attachmentForm.deviceModel" />
									</view>
								</u-form-item>
								<u-form-item>
									<u-input 
										v-model="attachmentForm.count" 
										placeholder="数量"
										@change="validateCount"
										/>
								</u-form-item>
							</u-form>
							<!--选择器搜索组件-->
							<pickerSearch v-model="isDeviceModel" :dataSource='deviceModelList' :pickerValues="[0]" @recload='attachmentValueConfirm'></pickerSearch>
						</view>
					</u-modal>
					<u-modal
						:show="isAddPropertiesValueOpen" 
						title="新增属性"
						@confirm="handleConfirmAddProperiesValue"
						@cancel="handleCancel" 
						show-cancel-button
						mask-close-able
						>
						<u-form :model="addPropertiesValueForm" ref="uForm" style="width: 100%;">
							<u-form-item>
								<text class="attach-item1" v-if="!addPropertiesValueForm.devicePropertiesEn" @click="basicPropertiesShow = true;">选择属性类型</text>
								<text class="attach-item1" v-else @click="basicPropertiesShow = true;">{{addPropertiesValueForm.devicePropertiesEn}}</text>
								<u-picker :show="basicPropertiesShow" :columns="unAttachPropertiesList" @confirm="unAttachPropertiesConfirm" keyName="label" @cancel="cancel"></u-picker>
							</u-form-item>
							<u-form-item>
								<text class="attach-item1" v-if="!addPropertiesValueForm.propertiesValue" @click="basicPropertiesValueShow = true;">选择值</text>
								<text class="attach-item1" v-else @click="basicPropertiesValueShow = true;">{{addPropertiesValueForm.propertiesValue}}</text>
								<u-picker :show="basicPropertiesValueShow" :columns="propertiesValueList" @confirm="propertiesValueConfirm" keyName="label" @cancel="cancel"></u-picker>
							</u-form-item>
						</u-form>
					</u-modal>
				</view>
				<view class="scan-item scan-item1">
					<input
						:focus="isFocus1" 
						placeholder="扫描或输入SN" 
						:value="deviceForm.deviceSn"
						@blur="confirm1" 
						type="text" 
						class="input">
					<view class="right-icon">
						<view class="icon" @click="doScan2">
							<u-icon size="30" name="scan"></u-icon>
						</view>
					</view>
				</view>
				<view class="scan-item scan-item1">
					<input
						:focus="isFocus2" 
						placeholder="扫描或输入An" 
						:value="deviceForm.deviceAn"
						@blur="confirm2" 
						type="text" 
						class="input">
					<view class="right-icon">
						<view class="icon" @click="doScan3">
							<u-icon size="30" name="scan"></u-icon>
						</view>
					</view>
				</view>
				<view class="scan-item scan-item1">
					<u-input v-model="deviceContent.name" placeholder="选择设备" disabled border="false" :show-action="false"></u-input>
				</view>
				<!-- <view class="scan-item scan-item1">
					<u-input v-model="deviceFit.name" @tap="handleSelectDeviceFit" placeholder="选择设备配置" border="false" :show-action="false"></u-input>
				</view> -->
				<view class="scan-item">
					<view class="test-scan">
						<picker v-model="deviceForm.deviceStatus" @change="statusChange" mode="selector" :range="statusList">
							<view :style="!deviceForm.deviceStatus ? 'color: #c2c6cd;' : ''">
								{{statusIndex === null ? deviceForm.deviceStatus || "选择设备状态" : statusList[statusIndex]}}
							</view>
						</picker>
					</view>
				</view>
				<view class="scan-item">
					<view class="test-scan">
						<picker v-model="deviceForm.deviceCondition" @change="deviceConditionChange" mode="selector" :range="deviceConditionList">
							<view :style="!deviceForm.deviceCondition ? 'color: #c2c6cd;' : ''">
								{{conditionIndex === null ? deviceForm.deviceCondition|| "选择设备成色" : deviceConditionList[conditionIndex]}}
							</view>
						</picker>
					</view>
				</view>
				<view class="scan-item scan-item1">
					<u-input v-model="deviceForm.remark" placeholder="请输入设备备注" border="false" :show-action="false"></u-input>
				</view>
				<view class="device-fault">
					<view class="fault-item">
						<view v-for="(group, faultPart) in deviceFaultList" :key="faultPart">
						  <h2>{{ faultPart }}</h2>
						  <u-checkbox-group
						  	placement="column"
						  >
						  	<u-checkbox
						  		:customStyle="{marginBottom: '8px'}"
						  		v-for="item in group"
						  		:key="item.id"
						  		:label="item.deviceFaultType"
						  		:name="item.deviceFaultType"
						  		:checked="item.checked"
						  		@change="handleFaultFixedChange(item)"
						  	>
						  	</u-checkbox>
						  </u-checkbox-group>
						</view>
					</view>
				</view>
				<view>
					<view>设备照片</view>
					<view>
						<u-upload 
							:fileList="fileList1" 
							@afterRead="afterRead" 
							@delete="deletePic" 
							name="1" 
							:maxCount="1">
						</u-upload>
					</view>
				</view>
				<view class="scan-item">
					<view class="button">
						<u-button type="primary" @click="changeDevice" text="确定修改设备" :disabled="buttonDisabled"></u-button>
					</view>
				</view>
			</view>
		</view>
		<view class="public">
			<text>备注：</text>
			<u--input 
				placeholder="请输入:" 
				height="10rpx" 
				type="textarea" 
				v-model="subForm.testRemark" 
				clearable>
			</u--input>
		</view>
		<view class="public">
			<view class="button">
				<u-button type="primary" @click="sub" text="提交" :disabled="buttonDisabled"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '@/utils/request';
	import {debounce} from '@/utils/debounce.js'
	import pickerSearch from '@/compoments/pickerSearch.vue'
	export default {
		name: 'main',
		components: {pickerSearch},
		onLoad(options) {
			uni.showLoading({
				title: "正在加载中"
			})
			this.getData(options.workId);
			this.workOrderId = options.workId
			this.getTypeCount(options.workId)
			this.getDeviceStatus()
			this.getDeviceCondition()
			// this.getDeviceFaultList()
			this.BaseUrl = getApp().globalData.baseURL;
			uni.hideLoading()
		},
		onUnload() {
			uni.$off('q-sign') //移除监听事件
		},
		data() {
			return {
				isDeviceModel: false,
				detailPropertiesValueList: [],
				deviceModelList: [],
				basicPropertiesShow: false,
				basicPropertiesValueShow: false,
				unAttachPropertiesList: [], // 不可拆卸属性列表
				addPropertiesValueForm: {},
				isAddPropertiesValueOpen: false,
				devicePropertiesShow: false,
				attachmentList: [], //配件表
				propertiesList: [], //属性表
				propertiesValueList: [], //属性值表 
				attachmentForm: {}, // 配件
				isAttachmentOpen: false, //配件弹窗
				workOrderId: '',
				deviceFaultForm: [],
				showFaultOpen: false, // 故障弹窗
				deviceTypeList:  [],
				faultType1: [], //记录设备详情
				deviceFaultList: [], //设备故障列表
				isFocus: true, // 二维码是否聚焦
				isFocus1: true, // sn是否聚焦
				isFocus2: true, // an是否聚焦
				deviceContent: {}, //选择设备传递的数据
				deviceFit: {}, //选择配置的页面
				statusList: [], //设备状态列表
				deviceStatus: null, //设备状态
				statusIndex: null, //select状态下标
				deviceConditionList: [], // 成色列表
				conditionIndex: null, //成色下标
				buttonDisabled: false,
				totalCount: 0, //设备数量
				proud: "",
				BaseUrl: "",
				dataForm: {}, // 数据工单
				historyList: [], //过程工单
				deviceForm: {
					deviceQr: null,
					deviceSn: null,
					deviceCondition:null,
					deviceAn: null,
					deviceStatus: null,
				}, //设备详情数据
				subForm: {
					workOrderId: null,
					method: "",
					testRemark: null
				}, //提交工单
				WorkOrderMediaBo: [], //工单文件
				enginnerWriteImagesFileUrl: '',
				userWriteImagesFileUrl: '',
				fileList1: [], //设备照片
				deviceImages: {
					deviceQr: '',
					mediaType: "1",
					mediaName: '设备照片',
					fileUrls: []
				},
				writeFlag: undefined,
			}
		},
		methods: {
			onnodeclick(node) {
				console.log(node)
			},
			// 新增基础配件属性
			handleConfirmAddProperiesValue() {
				request({
					url: "system/detailPropertiesValue",
					method:"POST",
					data: {
						...this.addPropertiesValueForm,
						ffDeviceQr: this.deviceForm.deviceQr,
					},
				}).then(res => {
					if (res.code === 200) {
						uni.showToast({
							title:"新增配件成功",
							icon:'none'
						})
						this.isAddPropertiesValueOpen = false
						this.addPropertiesValueForm = {}
						this.getDetailPropertiesValueList()
					} else {
						uni.showToast({
							title: res.msg,
							icon:'none'
						})
					}
				})
			},
			getDetailPropertiesValueList() {
				request({
					url: "system/detailPropertiesValue/list",
					method:"GET",
					data: {
						ffDeviceQr: this.deviceForm.deviceQr,
					},
				}).then(res => {
					this.detailPropertiesValueList = res.rows
				})
			},
			// 新增基础属性值
			handleAddProperiesValue() {
				this.isAddPropertiesValueOpen = true
				this.getUnAttachPropertiesList()
			},
			// 取消
			cancel() {
				this.devicePropertiesShow = false
				this.basicPropertiesShow = false
				this.basicPropertiesValueShow = false
			},
			// 确实基础配件类型
			unAttachPropertiesConfirm(e) {
				this.addPropertiesValueForm.devicePropertiesEn = e.value[0].devicePropertiesEn
				this.basicPropertiesShow = false
				this.getPropertiesValueList()
			},
			// 确定配件类型
			attachmentConfirm(e) {
				this.attachmentForm.deviceProperties = e.value[0].devicePropertiesEn
				this.attachmentForm.sourceFrom = e.value[0].sourceFrom
				this.devicePropertiesShow = false
			},
			// 确定配件型号
			attachmentValueConfirm(e) {
				// console.log("11", e)
				let result = this.deviceModelList.find(item => item.id === e.id);
				// console.log(result)
				this.attachmentForm.deviceModel = result.deviceModel
				this.attachmentForm.deviceModelId = result.deviceModelId
				this.attachmentForm.deviceType = result.deviceType
				this.attachmentForm.deviceBrand = result.deviceBrand
				this.attachmentForm.deviceTypeId = result.deviceTypeId
			},
			// 确定基础配件型号
			propertiesValueConfirm(e) {
				this.addPropertiesValueForm.propertiesValue = e.value[0].propertiesValue
				this.basicPropertiesValueShow = false
			},
			// 删除基础属性配件
			handleCancelPropertiesValue() {
				const self = this; // 保存当前对象的引用
				uni.showModal({
					title: '确定删除该配件吗',
					success: function (res) {
						if (res.confirm) {
							// 提交
							request({
								url: `system/detailPropertiesValue/${item.id}`,
								method: "delete",
							}).then(res => {
								if (res.code === 200) {
									uni.showToast({
										title:'删除配件成功',
										icon:'none'
									})
									self.getDetailPropertiesValueList()
								} else {
									uni.showToast({
										title: res.msg,
										icon:'none'
									})
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			// 删除配件
			handleCancelAttachment(item) {
				const self = this; // 保存当前对象的引用
				uni.showModal({
					title: '确定删除该配件吗',
					success: function (res) {
						if (res.confirm) {
							// 提交
							request({
								url: `system/detailAttachment/${item.id}`,
								method: "delete",
							}).then(res => {
								if (res.code === 200) {
									uni.showToast({
										title:'删除配件成功',
										icon:'none'
									})
									self.getAttachmentList()
								} else {
									uni.showToast({
										title: res.msg,
										icon:'none'
									})
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			// 获取配件表
			getAttachmentList() {
				request({
					url: "system/detailAttachment/list",
					method:"GET",
					data: {
						ffDeviceQr: this.deviceForm.deviceQr,
					},
				}).then(res => {
					this.attachmentList = res.rows
				})
			},
			// 验证配件数量
			validateCount(event) {
				if (this.attachmentForm.count % 1 === 0) {
					uni.showToast({
						title:'请输入整数',
						icon:'none'
					})
				} else if (this.attachmentForm.count < 0) {
					uni.showToast({
						title:'不允许输入负数',
						icon:'none'
					})
				}
			},
			// 新增配件关联
			handleConfirmAdd() {
				request({
					url: "system/detailAttachment",
					method:"POST",
					data: {
						...this.attachmentForm,
						ffDeviceQr: this.deviceForm.deviceQr,
						ifAlreadyDisassembly: 0
					},
				}).then(res => {
					if (res.code === 200) {
						uni.showToast({
							title:"新增配件成功",
							icon:'none'
						})
						this.isAttachmentOpen = false
						this.attachmentForm = {
							deviceModel: '',
							deviceProperties: ''
						}
						this.getAttachmentList()
					} else {
						uni.showToast({
							title: res.msg,
							icon:'none'
						})
					}
				})
			},
			// 取消新增配件
			handleCancel() {
				this.isAttachmentOpen = false
				this.isAddPropertiesValueOpen = false
				this.attachmentForm = {
					deviceModel : "",
					deviceProperties: "",
					sourceFrom: ""
				}
				this.addPropertiesValueForm = {}
			},
			// 新增配件
			handleAddAttachment() {
				this.isAttachmentOpen = true
				this.attachmentForm.count = 1
				this.getPropertiesList()
			},
			// 获取不可拆卸属性列表	
			getUnAttachPropertiesList() {
				request({
					url: "system/typeProperties/list",
					method:"GET",
					data: {
						deviceTypeId: this.deviceForm.deviceTypeId,
						ifAttachment: false
					},
				}).then(res => {
					this.unAttachPropertiesList = res.rows.map((item, index) => ({
					    label: item.devicePropertiesCn + "/" + item.devicePropertiesEn,
						devicePropertiesEn: item.devicePropertiesEn,
					    id: index
					}));
					this.unAttachPropertiesList = [this.unAttachPropertiesList]
				})
			},
			// 配件属性
			getPropertiesList() {
				request({
					url: "system/typeProperties/list",
					method:"GET",
					data: {
						deviceType: this.deviceForm.deviceType,
						ifAttachment: true
					},
				}).then(res => {
					this.propertiesList = res.rows.map((item, index) => ({
					    label: item.devicePropertiesCn + "/" +item.devicePropertiesEn,
						devicePropertiesEn: item.devicePropertiesEn,
						sourceFrom: item.sourceFrom,
					    id: index
					}));
					this.propertiesList = [this.propertiesList]
				})
			},
			// 获取配件型号
			getDeviceModelList() {
				request({
					url: "system/modelLibrary/list",
					method:"GET",
					data: {
						deviceTypeId: this.attachmentForm.sourceFrom,
						method: "source_from"
					},
				}).then(res => {
					this.deviceModelList = res.rows.map((item, index) => ({
						...item,
						name: item.deviceType + '/' + item.deviceModel,
						id: index
					}));
					this.isDeviceModel = true
				})
			},
			// 配件属性值
			getPropertiesValueList() {
				request({
					url: "system/typePropertiesValue/list",
					method:"GET",
					data: {
						deviceTypeId: this.deviceForm.deviceTypeId,
						devicePropertiesEn: this.addPropertiesValueForm.devicePropertiesEn
					},
				}).then(res => {
					this.propertiesValueList = res.rows.map((item, index) => ({
					    label: item.deviceType + '/' + item.propertiesValue,
						propertiesValue: item.propertiesValue,
					    id: index
					}));
					this.propertiesValueList = [this.propertiesValueList]
				})
			},
			// 设备故障checkbox
			handleFaultFixedChange(item) {
				item.checked= !item.checked
				// console.log(item)
				if (item.checked) {
				    if (this.deviceFaultForm.indexOf(item.deviceFaultType) === -1) {
				        this.deviceFaultForm.push(item.deviceFaultType);
				    }
				} else {
				    const index = this.deviceFaultForm.indexOf(item.deviceFaultType);
				    if (index !== -1) {
				        this.deviceFaultForm.splice(index, 1);
				    }
				}
			},
			// 填加设备故障
			addFaultDevice() {
				this.showFaultOpen = true;
				// this.getDeviceFaultList()
			},
			// 设备故障列表
			getDeviceFaultList(deviceTypeId) {
				request({
					url: "system/faultType/list",
					method:"GET",
					data: {
						deviceTypeId: deviceTypeId
					},
				}).then(res => {
					// this.deviceFaultList = res.rows
					this.deviceFaultList = this.groupFaults(res.rows);
				})
			},
			groupFaults(faults) {
				const grouped = {};
				faults.forEach(fault => {
					if (!grouped[fault.faultPart]) {
						grouped[fault.faultPart] = [];
					}
					const faultWithChecked = { ...fault, checked: false }; // 添加 checked 属性并赋值为 false
					grouped[fault.faultPart].push(faultWithChecked);
				});
			
				Object.keys(grouped).forEach(faultPart => {
					const devices = grouped[faultPart];
					devices.forEach(device => {
						if (this.deviceFaultForm.includes(device.deviceFaultType)) {
							device.checked = true;
						}
					});
				});
			
				return grouped;
			},
			// 确定添加设备
			confirmDoubleDevice(data) {
				// console.log(data, '选择的数据')
				this.deviceFaultForm.push({
					faultType: data.name,
					checked: true
				})
			},
			// 获取选择设备返回的参数
			otherFun(item) {
				if (item) {
					this.deviceFit = item
					// console.log("other", this.deviceFit)
					let firstSlashIndex = item.name.indexOf("/"); // 第一个斜杠的位置
					let secondSlashIndex = item.name.indexOf("/", firstSlashIndex + 1); // 第二个斜杠的位置
					let thirdSlashIndex = item.name.indexOf("/", secondSlashIndex + 1); // 第三个斜杠的位置
						
					this.deviceContent.name = item.name.substring(0,thirdSlashIndex);
					this.deviceFit.name = item.name
					this.deviceContent.id = item.fId || this.deviceForm.deviceModelId
				}
			},
			// 二维码确定
			confirm(e) {
				this.isFocus = false
				this.deviceForm.deviceQr = e.detail.value
				this.getDeviceData()
			},
			// sn
			confirm1(e) {
				this.isFocus1 = false
				this.deviceForm.deviceSn = e.detail.value
			},
			// An
			confirm2(e) {
				this.isFocus2 = false
				this.deviceForm.deviceAn = e.detail.value
			},
			// 选择设备配置
			handleSelectDeviceFit() {
				const workId = this.dataForm.workOrderId
				uni.navigateTo({
					url: 'deviceFit?workId=' + workId
				});
			},
			// 设备状态列表
			getDeviceStatus() {
				request({
					url: "system/dict/data/list",
					method:"GET",
					data: {
						dictType: "devicestatus"
					},
				}).then(res => {
					this.statusList = res.rows.map((item) => item.dictValue)
				})
			},
			// 获取型号比
			getTypeCount(workId) {
				request({
					method: "GET",
					url: 'system/detail/statistics',
					data: {
						workOrderId: workId,
						deviceFlowStatus:"已检测",
					}
				}).then(res => {
					this.deviceTypeList = res.rows
				})
			},
			// 设备成色列表
			getDeviceCondition() {
				request({
					url: "system/dict/data/list",
					method:"GET",
					data: {
						dictType: "device_condition"
					},
				}).then(res => {
					this.deviceConditionList = res.rows.map((item) => item.dictValue)
				})
			},
			// 设备状态
			statusChange(e) {
				this.statusIndex = e.detail.value
				this.deviceForm.deviceStatus = this.statusList[this.statusIndex]
			},
			// 设备成色
			deviceConditionChange(e) {
				this.conditionIndex = e.detail.value
				this.deviceForm.deviceCondition = this.deviceConditionList[this.conditionIndex]
			},
			// 扫码id
			doScan1() {
				uni.scanCode({
					success: (res) =>{
						this.deviceForm.deviceQr = res.result
						this.getDeviceData()
					}
				})
			},
			// 扫码sn
			doScan2() {
				uni.scanCode({
					success: (res) => {
						this.deviceForm.deviceSn = res.result
					}
				})
			},
			// An
			doScan3() {
				uni.scanCode({
					success: (res) => {
						this.deviceForm.deviceAn = res.result
					}
				})
			},
			goSign(num) {
				this.writeFlag = num;
				uni.navigateTo({
					url: '/uni_modules/q-sign/pages/q-sign'
				})
			},
			// 修改设备
			changeDevice() {
				this.deviceForm.faultTypes = this.deviceFaultForm
				let { deviceModelId, ffModelId,  ...otherDeviceForm } = this.deviceForm;
				let requestParams = {
					...otherDeviceForm,
					deviceModelId: this.deviceFit.id,
					deviceQr: this.deviceForm.deviceQr,
					deviceSn: this.deviceForm.deviceSn,
					deviceAn: this.deviceForm.deviceAn,
					deviceStatus: this.deviceForm.deviceStatus,
					deviceFlowStatus: "已检测",
					ffModelId: this.deviceContent.id,
					workOrderId: this.dataForm.workOrderId,
					deviceCondition: this.deviceForm.deviceCondition,
				}
				
				if (JSON.stringify(this.deviceForm.faultTypes) !== JSON.stringify(this.faultType1)) {
					requestParams.method = '1';
				}
				this.deviceImages.deviceQr = this.deviceForm.deviceQr
				request({
					method: "GET",
					url: `system/detail/${this.deviceForm.deviceQr}`,
				}).then((res) => {
					if (res.data) {
						const self = this;
						request({
							url: "system/detail",
							method:"put",
							data: requestParams,
						}).then(res => {
							if (res.code === 200) {
								uni.showToast({
									title:"修改成功",
									icon:'none'
								})
								self.reset()
								self.getTypeCount(self.workOrderId)
								self.fileList1 = []
								self.deviceFaultList = []
							} else {
								uni.showToast({
									title: res.msg,
									icon:'none'
								})
							}
						})
						// 设备照片
						if (self.deviceImages.fileUrls.length > 0) {
							request({
								url: 'system/modelMedia',
								method: 'POST',
								data: self.deviceImages
							}).then(res => {
								console.log("图片上传成功")
							})
						}
					} else {
						const self = this; // 保存当前对象的引用
						uni.showModal({
							title: '该设备不存在，是否要新增',
							success: function (res) {
								if (res.confirm) {
									// 修改设备
									request({
										url: "system/detail",
										method:"put",
										data: requestParams,
									}).then(res => {
										if (res.code === 200) {
											uni.showToast({
												title:"新增成功",
												icon:'none'
											})
											self.reset()
											self.getTypeCount(self.workOrderId)
											self.fileList1 = []
											self.deviceFaultList = []
										}	else {
											uni.showToast({
												title: res.msg,
												icon:'none'
											})
										}
									})
									// 设备照片
									if (self.deviceImages.fileUrls.length > 0) {
										request({
											url: 'system/modelMedia',
											method: 'POST',
											data: self.deviceImages
										}).then(res => {
											console.log("图片上传成功")
										})
									}
								} else if (res.cancel) {
									self.reset()
									self.fileList1 = []
									self.deviceFaultList = []
								}
							}
						})
					}
				})
			},
			sub() {
				this.subForm.workOrderId = this.dataForm.workOrderId
				this.subForm.method = "end_test"
				const self = this; // 保存当前对象的引用
				uni.showModal({
					title: '确定结束检测吗',
					success: function (res) {
						if (res.confirm) {
							// 提交
							request({
								url: 'system/order',
								method: "PUT",
								data: self.subForm
							}).then(res => {
								uni.reLaunch({
									url: '/pages/view/inspect/index'
								})
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.forEach((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, event.name)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, name) {
				return new Promise((resolve, reject) => {
					uni.$u.http.upload(`${this.BaseUrl}system/oss/upload`, {
						params: {},
						/* 会加在url上 */
						// #ifdef APP-PLUS || H5
						files: [], // 需要上传的文件列表。使用 files 时，filePath 和 name 不生效。App、H5（ 2.6.15+）
						// #endif
						filePath: url, // 要上传文件资源的路径。
						// 注：如果局部custom与全局custom有同名属性，则后面的属性会覆盖前面的属性，相当于Object.assign(全局，局部)
						custom: {
							auth: true
						}, // 可以加一些自定义参数，在拦截器等地方使用。比如这里我加了一个auth，可在拦截器里拿到，如果true就传token
						name: 'file', // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
						// #ifdef H5 || APP-PLUS
						timeout: 60000, // H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)
						// #endif
						header: {
							Authorization: uni.getStorageSync("token")
						},
						/* 会与全局header合并，如有同名属性，局部覆盖全局 */
						formData: {}, // HTTP 请求中其他额外的 form data
						// 返回当前请求的task, options。请勿在此处修改options。非必填
						getTask: (task, options) => {},
					}).then((res) => {
						console.log(res);
						if (name == 1) {
							this.deviceImages.fileUrls.push(
								res.data.data.url.replace("blob:", ""),
							)
						}
						resolve(res.data.data.url)
						// 返回的res.data 已经进行JSON.parse
					}).catch(err => {

					})
				})
			},
			// 请求数据
			getData(workId) {
				request({
					method: "GET",
					url: `system/order/${workId}`
				}).then(res => {
					this.dataForm = res.data;
					this.subForm.workOrderId = res.data.workOrderId;
					this.proud = res.data.workOrderStatusId - 0;
					this.demark(res.data);
				})
			},
			// 选择设备数据
 			reset() {
				this.deviceForm = {}
				this.deviceContent = {}
				this.deviceFit = {}
				this.deviceFaultForm = []
				this.attachmentList = []
				this.detailPropertiesValueList = []
			},
			// 设备详情数据
			debounceGetDevice: debounce(function() {
				if (this.deviceForm.deviceQr.trim() !== '') {
					this.getDeviceData()
				}
			}, 1000),
			// 获取单个设备详情
			getDeviceData() {
				request({
					method: "GET",
					url: `system/detail/${this.deviceForm.deviceQr}`,
				}).then(res => {
					if (res.data) {
						this.deviceForm = res.data
						this.faultType1 = res.data.deviceFaultVos
						// this.fileList1 = res.data.modelMediaVos
						this.checkImages(res.data.deviceModelMediaVos)
						// 选择设备类型
						const specs1 = JSON.parse(res.data.deviceSpecs || "[]");
						const formattedData = specs1.map(item => item[2]);
						// 将数组转换为以斜杠分隔的字符串
						const resultString = formattedData.join('/');
						this.deviceContent.name = `${res.data.deviceType}/${res.data.deviceBrand}/${res.data.deviceModel}`
						this.deviceContent.id = res.data.deviceModelId
						this.deviceFit.name = resultString
						if (res.data.deviceFaultVos.length !== 0) {
							this.deviceFaultForm = res.data.deviceFaultVos.map(item => item.faultType);
						}
						if (res.data.deviceType) {
							this.getDeviceFaultList(res.data.deviceTypeId)
						}
						this.getAttachmentList()
						this.getDetailPropertiesValueList()
					}
				})
			},
			// 存储图片
			checkImages(imageForms) {
				for (let dataElement of imageForms) {
					switch (dataElement.mediaType) {
						case "1": 
							if (dataElement.fileUrl !== null) {
								this.fileList1.push({
									type: "image",
									url: dataElement.fileUrl,
									status: "success",
									name: "",
									message: "",
									thumb: "",
									size: 60489
								})
							}
						default:
							continue;
					}
				}
			},
			// 流程
			demark(data) {
				this.historyList.push({
					id: 0,
					descTime: data.preArriveCustomerTime,
					title: '预计上门时间',
					istrue: !!data.preArriveCustomerTime && true
				}, {
					id: 1,
					descTime: data.pickOrderTime,
					title: '接单时间',
					istrue: !!data.pickOrderTime && true
				}, {
					id: 2,
					descTime: data.arriveCustomerTime,
					title: '上门时间',
					istrue: !!data.arriveCustomerTime && true
				}, {
					id: 3,
					descTime: data.startRecycleTime,
					title: '开始回收时间 ',
					istrue: !!data.startRecycleTime && true
				}, {
					id: 4,
					descTime: data.endRecycleTime,
					title: '结束回收时间',
					istrue: !!data.endRecycleTime && true
				})
			}
		},
		filters: {
			formatDate: function(value, args) {
				var dt = new Date(value);
				if (args == 'yyyy-M-d') { // yyyy-M-d
					let year = dt.getFullYear();
					let month = dt.getMonth() + 1;
					let date = dt.getDate();
					return `${year}-${month}-${date}`;
				} else if (args == 'yyyy-M-d H:m:s') { // yyyy-M-d H:m:s
					let year = dt.getFullYear();
					let month = dt.getMonth() + 1;
					let date = dt.getDate();
					let hour = dt.getHours();
					let minute = dt.getMinutes();
					let second = dt.getSeconds();
					return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
				} else if (args == 'yyyy-MM-dd') { // yyyy-MM-dd
					let year = dt.getFullYear();
					let month = (dt.getMonth() + 1).toString().padStart(2, '0');
					let date = dt.getDate().toString().padStart(2, '0');
					return `${year}-${month}-${date}`;
				} else { // yyyy-MM-dd HH:mm:ss
					let year = dt.getFullYear();
					let month = (dt.getMonth() + 1).toString().padStart(2, '0');
					let date = dt.getDate().toString().padStart(2, '0');
					let hour = dt.getHours().toString().padStart(2, '0');
					let minute = dt.getMinutes().toString().padStart(2, '0');
					let second = dt.getSeconds().toString().padStart(2, '0');
					return `${month}-${date} ${hour}:${minute}`;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	._abbr {
		width: 100%;
		height: 100%;
		// position: absolute;
		background-color: rgba(244, 249, 254, 1);

		.public {
			background-color: #ffffff;
			margin: 20upx;
			border-radius: 2%;
			padding: 20upx;
			border:1px solid;
			border-color:rgba(0, 124, 233, 0.4);
			.main_body_view {
				margin: 10upx;
			}
			.device-count {
				display: flex;
				margin: 10px 0;
				flex-flow: row wrap;
				align-content: flex-start;
				justify-content: flex-start;
				>view {
					box-sizing: border-box;
					flex: 0 0 33%;
					text-align: center;
				}
				.device-item {
					display: flex;
					flex-direction: column;
					padding:5px;
				}
			}
			.main_body_view_title {
				border-bottom: 1px solid black;
				margin-bottom: 10upx;
			}
			.device-fault {
				border: 1px solid #eee;
				.fault-item {
					display: flex;
					flex-flow: row wrap;
					align-content: flex-start;
					justify-content: flex-start;
					// justify-content: space-around;
					>view {
						box-sizing: border-box;
						flex: 0 0 33%;
						text-align: center;
						// margin-top: 20rpx;
						// border: 1px solid #00f;
						// height: 40px;
					}
				}
			}
			.scan-item {
				margin: 10px 0;
				.input {
					margin: 10px 0 10px 6px;
					width: 100%;
				}
				.add-attachment {
					padding: 4px 10px; 
					width: 70px; 
					border: 1px solid #eee
				}
				.add-attachmentBasic {
					padding: 4px 10px; 
					width: 120px; 
					margin-left: 10px;
					border: 1px solid #eee
				}
				.attach-item {
					border: 1px solid #eee;
					width: 230px;
					padding: 8px;
				}
				.attach-item1 {
					border: 1px solid #eee; 
					width: 230px;
					padding: 8px;
				}
				.item-container {
				  .item {
				    box-sizing: border-box; /* 让边框和填充不会增加项目的宽度 */
				    padding: 5px; /* 可以根据需要调整间距 */
				    .cancel {
				      margin-left: 6px;
				      cursor: pointer;
				      color: #409eff;
				    }
				  }
				}
				.right-icon {
					position: relative;
					box-sizing: border-box;
					position: sticky;
					top: 0;
					z-index: 999;
					display: flex;
					overflow: hidden;
					justify-content: space-around;
					background: rgb(255, 255, 255);
					margin: 6px;
					.scan {
						position: absolute;
						top: 8upx;
						right: 14px;
					}
				}
				
				.test-scan {
					border: 1px solid #eee;
					padding: 8px;
				}
			}
			.scan-item1 {
				display: flex; 
				border: 1px solid #eee;
			}
			.device {
				display: flex;
				justify-content: space-between;
				margin: 10px 0;
			}
			.device-item {
				display: flex;
				flex-direction: column;
			}
			.user_for {
				display: flex;
			}
			.line_for {
				width: 4rpx;
				height: 24rpx;
				margin: 0 20rpx 10rpx;
			}
			.line_radio {
				width: 20rpx;
				height: 20rpx;
				border-radius: 50%;
				position: relative;
				left: 50%;
				transform: translateX(-50%);
				top: 0;
			}
			.right_box {
				padding: 0rpx 20rpx 20rpx 20rpx;
			}
			.desc {
				font-size: 30rpx;
				display: flex;
				margin-top: 20rpx;
				align-items: center;
			}
		}
		.write {
			display: flex;
			justify-content: space-around;
			.im {
				width: 300rpx;
				image {
					width: 200rpx;
					height: 300rpx;
					position: relative;
					left: 30rpx;
				}
			}
		}
	}
</style>